package com.newcapec.shiro.service.impl;

import com.newcapec.shiro.constant.SystemCode;
import com.newcapec.shiro.dao.UsersDao;
import com.newcapec.shiro.entity.UserInfo;
import com.newcapec.shiro.entity.Users;
import com.newcapec.shiro.exception.CustomException;
import com.newcapec.shiro.service.UsersService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
@Slf4j
@Service
public class UsersServiceImpl implements UsersService {
    @Resource
    private UsersDao usersDao;
    @Override
    public void add(Users entity) {

    }

    @Override
    public void edit(Users entity) {

    }

    @Override
    public void remove(Integer id) {

    }

    @Override
    public void removeBatch(Integer[] id) {

    }

    @Override
    public Users findById(Integer id) {
        return null;
    }

    @Override
    public Map<String, Object> find(Integer pageNum, Integer pageSize, Users entity) {
        return null;
    }

    @Override
    public List<Users> findAll() {
        return null;
    }

    @Override
    public Boolean exists(String username) {
        return null;
    }

    @Override
    public UserInfo login(String username, String password) {
        Subject subject = SecurityUtils.getSubject();

        //判断用户是否登录
        if(!subject.isAuthenticated()){
            UsernamePasswordToken usernamePasswordToken=new UsernamePasswordToken(username,password);
            try {
                subject.login(usernamePasswordToken);
            }catch(Exception e){
                log.info("@myMessage:用户名不存在");
                throw new CustomException(SystemCode.UsernameError.getCode(),SystemCode.UsernameError.getMessage());
            }

        }

        UserInfo userInfo = (UserInfo) subject.getPrincipal();
        //将会话的唯一标识作为用户的token
//        userInfo.setToken(subject.getSession().getId());
        return userInfo;

    }

    @Override
    public UserInfo findByUsername(String username) {
        /**
         * Spring中的工具类可以实现对象复制，复制的为对象中的属性值
         */
        Users users = usersDao.selectByUsername(username);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(users, userInfo);
        return userInfo;
    }
}
